from bs4 import BeautifulSoup
import os
from config import (
    my_data_weather,
    my_weather_tips,
    my_travel_tips,
    my_text_search_result,
    my_tour_plan,
    my_template_filename,
    my_output_filename,
    my_title,
    my_city,
    my_taxi_uri_list,
)

def get_soup_from_template(template_filename:str=my_template_filename)->BeautifulSoup:
    with open(template_filename) as fp:
        soup = BeautifulSoup(fp, 'lxml')
    return soup

def render_title_h1(soup:BeautifulSoup, city:str=my_city)->BeautifulSoup:
    soup.find_all('title')[0].string = city + '旅游建议'
    soup.find_all('h1')[0].string = city + '旅游建议'
    return soup

def render_data_weather(soup:BeautifulSoup, data_weather:dict=my_data_weather)->BeautifulSoup:
    # render weather card
    print(f'type_of_data_weather: {type(data_weather)}\ndata_weather:\n{data_weather}')
    for n, weather_card in enumerate(soup.find_all("div", class_='weather-card')):
        # print(weather_card)
        child_list = list(weather_card.children)
        # print(len(child_list))
        # for i, child in enumerate(child_list):
        #     print(f'{i}: {child}')
        print(f'child_list:\n{child_list}')
        print(f'data_weather:\n{data_weather}')
        data_weather_forecasts = data_weather['forecasts'] # Only for test
        print(f'data_weather_forecasts:\n{data_weather_forecasts}')
        child_list[1].string = data_weather['forecasts'][n]['date']
        child_list[3].string = '白天温度：' + data_weather['forecasts'][n]['daytemp'] + '℃'
        child_list[5].string = '夜晚温度：' + data_weather['forecasts'][n]['nighttemp'] + '℃'
    return soup

def render_weather_tips(soup:BeautifulSoup, weather_tips:dict=my_weather_tips)->BeautifulSoup:
    tip_content_div = soup.find_all('div',class_='tip-content')[0]
    child_list = list(tip_content_div.children)
    # print(len(child_list))
    # for i, child in enumerate(child_list):
    #     print(f'{i}: {child}')
    print(f'child_list:\n{child_list}')
    print(f'weather_tips_keys:\n{list(weather_tips.keys())}')
    print(f'weather_tips_values:\n{list(weather_tips.values())}')
    child_list[1].string = list(weather_tips.keys())[0] + ': ' + list(weather_tips.values())[0]
    child_list[3].string = list(weather_tips.keys())[1] + ': ' + list(weather_tips.values())[1]
    child_list[5].string = list(weather_tips.keys())[2] + ': ' + list(weather_tips.values())[2]
    return soup

# def render_tour_plan(soup:BeautifulSoup, tour_plan:dict=my_tour_plan)->BeautifulSoup:
#     # render day div
#     for n, day_div in enumerate(soup.find_all("div", class_='day')):
#         child_list = list(day_div.children)
#         # print(len(child_list))
#         # for i, child in enumerate(child_list):
#         #     print(f'{i}: {child}')
#         child_list[1].string = list(tour_plan.keys())[n]

#         for k, img_tag in enumerate(child_list[3].find_all('img')):
#             img_tag['src'] = list(tour_plan.values())[n][k][1]
#             img_tag['alt'] = list(tour_plan.values())[n][k][0]
        
#         for k, h3_tag in enumerate(child_list[3].find_all('h3')):
#             h3_tag['h3'] = list(tour_plan.values())[n][k][0]
        
#         for k, p_tag in enumerate(child_list[3].find_all('p')):
#             p_tag.string = '建议游览时间' + list(tour_plan.values())[n][k][2]

#         # child_list[5].string = '从place1到place2打车'
#         # child_list[7].string = '从place2到place3打车'
#     return soup

def render_travel_tips(soup:BeautifulSoup, travel_tips:dict=my_travel_tips, text_search_result:dict=my_text_search_result, taxi_uri_list:list[str]=my_taxi_uri_list)->BeautifulSoup:
    print(f'text_search_result:\n{text_search_result}')
    position_metadata = {record_dict['name']:[record_dict['address'],record_dict['photo']] for record_dict in text_search_result}
    # render day div
    for n, day_div in enumerate(soup.find_all("div", class_='day')):
        child_list = list(day_div.children)
        # print(len(child_list))
        # for i, child in enumerate(child_list):
        #     print(f'{i}: {child}')
        child_list[1].string = list(travel_tips.keys())[n]

        for k, img_tag in enumerate(child_list[3].find_all('img')):
            
            print('list_travel_tips_values_n_k\n'+str(list(travel_tips.values())[n][k]))
            img_tag['alt'] = list(list(travel_tips.values())[n][k].keys())[0]
            img_tag['src'] = position_metadata[img_tag['alt']][1] if img_tag['alt'] in position_metadata.keys() else ''
        
        for k, h3_tag in enumerate(child_list[3].find_all('h3')):
            h3_tag.string = list(list(travel_tips.values())[n][k].keys())[0]
        
        for k, p_tag in enumerate(child_list[3].find_all('p')):
            p_tag.string = '建议游览时间：' + list(list(travel_tips.values())[n][k].values())[0][0] + '-' + list(list(travel_tips.values())[n][k].values())[0][1]

        print(f'child_list_5\n{child_list[5]}')
        print(f'child_list_7\n{child_list[7]}')
        child_list[5].find_all('a')[0].string = '一键打车: ' + list(list(travel_tips.values())[n][0].keys())[0] + '->' + list(list(travel_tips.values())[n][1].keys())[0]
        child_list[5].find_all('a')[0]['href'] = taxi_uri_list[n][0]
        child_list[7].find_all('a')[0].string = '一键打车: ' + list(list(travel_tips.values())[n][1].keys())[0] + '->' + list(list(travel_tips.values())[n][2].keys())[0]
        child_list[7].find_all('a')[0]['href'] = taxi_uri_list[n][1]

    return soup

def soup_to_html_content(soup:BeautifulSoup) -> str:
    return soup.prettify()

def content_to_html_file(content:str, output_filename:str=my_output_filename) -> str:
    os.makedirs(os.path.dirname(output_filename), exist_ok=True)
    with open(output_filename, 'w', encoding='utf-8') as file:
      file.write(content)
    return output_filename

def render_whole_html(
        data_weather:dict=my_data_weather, 
        weather_tips:dict=my_weather_tips,
        text_search_result:dict=my_text_search_result,
        travel_tips:dict=my_travel_tips, 
        city:str=my_city,
        template_filename:str=my_template_filename, 
        )->str:
    """Render the whole html page"""
    soup = get_soup_from_template(template_filename)
    soup = render_title_h1(soup, city=city)
    soup = render_data_weather(soup, data_weather)
    soup = render_weather_tips(soup, weather_tips)
    soup = render_travel_tips(soup, travel_tips,text_search_result=text_search_result)
    
    return soup_to_html_content(soup)


if __name__ == '__main__':
    render_whole_html()
    